package com.itheima.controller;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.itheima.entity.common.Result;
import com.itheima.service.WeiXinPayService;

@RestController
@RequestMapping("/pay")
public class PayController {
	

	@Autowired
	private WeiXinPayService weiXinPayService;

	/**
     * 创建二维码
	 */
	@RequestMapping("/createNative")
	public Map<String,String> createNative(String out_trade_no){

	  return weiXinPayService.createNative(out_trade_no, "11656");
	}

    /**
     * 查询支付订单状态(结果)
     */
	@RequestMapping("/queryPayStatus")
	public Result queryPayStatus(String out_trade_no)throws Exception{
		Result result = null;
		int count = 0;
		while(true){
			Map<String,String> map = weiXinPayService.queryPayStatus(out_trade_no);
			if(map.isEmpty()){
				result=new Result(false, "支付发生错误");
				break;
			}
			if(map.get("trade_state").equals("SUCCESS")){// 支付成功
				result=new Result(true, "支付成功");
				//orderService.updateOrderStatus(out_trade_no, map.get("transaction_id"));
				break;
			}

			// 避免一直调用,适当休眠
			Thread.sleep(3000);
            count ++;
			if(count >= 100){
				result=new Result(false, "二维码超时");
				break;
			}
		}
		return result;
	}

	
}
